package com.futong.cloud.action;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.futong.cloud.dao.entity.CloudClient;
import com.futong.cloud.utils.ClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

@Slf4j
public class ActionFactory {
    public static JSONObject handler(JSONObject request){
        log.info("action 请求对象参数详情： {}"+request);
        String action,clientId;CloudClient client = null;
        Assert.notNull(request,"请求对象request为空");
        Assert.isTrue(StringUtils.isNotEmpty(action=request.getString("action")),"action不能为空");
        if(StringUtils.isNotEmpty(clientId = request.getString("clientId"))) {
            Assert.notNull(client= ClientUtils.getClient(clientId),"未找到云client信息");
            action+="_"+client.getCloudType()+"_"+client.getCloudVersion();
        }
        ActionModel actionModel = ActionRegister.getActions().get(action);
        Assert.notNull(actionModel,"该请求方法对应的处理尚未注册");
        //封装标签处理上下文
        ActionContext context=new ActionContext(request,actionModel);
        if(Objects.nonNull(client)){
            context.setCloudClient(client);
        }
        //发起处理调用
        handler(context);
        log.info("action 返回参数详情： [{}]"+context.getResponse());
        return success(context.getResponse());
    }
    public static void handler(ActionContext context){
        for (ActionModel.ActionFunctionModel function : context.getActionModel().getFunctions()) {
            if(context.stop)break;
            function.consumer.accept(context);
        }
    }

    public static JSONObject success(Object data){
        JSONObject success=new JSONObject();
        success.put("data",data);
        success.put("success",true);
        success.put("code",200);
        success.put("message","操作成功");
        return success;
    }
    public static JSONObject success(){
        JSONObject success=new JSONObject();
        success.put("success",true);
        success.put("code",200);
        success.put("message","操作成功");
        return success;
    }
    public static JSONObject fail(String message,Integer code){
        JSONObject success=new JSONObject();
        success.put("success",false);
        success.put("code",code);
        success.put("message",message);
        return success;
    }
    public static JSONObject fail(String message){
        return fail(message,500);
    }
}
